package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.constant.RabbitConst;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.config.component.RabbitService;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @Author:lyd
 * @Date:2023/9/7 11:16
 * @Version:1.0
 * @Description
 **/
@Service
@Slf4j
public class OrderPayedListener {


    @Autowired
    OrderBizService orderBizService;
    @Autowired
    RabbitService rabbitService;

    @RabbitListener(queues = RabbitConst.QUEUE_ORDER_PAYED)
    public void handle(Message message, Channel channel) throws IOException {

        String msgJson = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {

            //1、获取消息
            Map<String, String> msg = JSONs.jsonToObj(msgJson, new TypeReference<Map<String, String>>() {
            });
            //2、处理业务
            //修改订单状态，此时的状态为未支付-> 已关闭、未支付->已支付
            orderBizService.payOrderStatus(msg);

            //3、处理成功，手动确认，服务器可以删除该消息了
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            //4、处理失败，启动重试机制
            log.info("订单修改为已支付状态失败：原因", e.getMessage());
            rabbitService.reTry(msgJson,channel,deliveryTag,5);

        }
    }
}
